package com.example.test.support.interceptor;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class UploadFileRequestInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url();
        // 判断是否为 237 或 qiantoon.tech 平台的 图片上传，若是，则转换请求地址
        if ((url.host().contains("124.161.168.237") || url.host().contains("qiantoon.tech"))
                && url.encodedPath().contains("UpLoadFile")) {
            Request.Builder builder = request.newBuilder();
            HttpUrl.Builder httpBuilder = url.newBuilder()
                    .host("124.161.168.237")
                    .port(8093)
                    .scheme("http");
            int size = url.pathSegments().size();
            for (int index = 0; index < size; index++) {
                httpBuilder.removePathSegment(0);
            }
            HttpUrl newUrl = httpBuilder
                    .addPathSegment("QiantoonService")
                    .addPathSegment("Comm")
                    .addPathSegment("UpLoadFile")
                    .build();
            return chain.proceed(builder.url(newUrl).build());
        } else {
            return chain.proceed(request);
        }
    }
}
